/**  
 * All rights Reserved, Designed By www.shatayy.com
 * @Title:  ${file_name}   
 * @Package ${package_name}   
 * @Description:    ${todo}(用一句话描述该文件做什么)   
 * @author: 宁波沙塔信息技术有限公司     
 * @date:   ${date} ${time}   
 * @version V1.0 
 * @Copyright: ${year} www.tydic.com Inc. All rights reserved. 
 * 注意：本内容仅限于宁波沙塔信息技术股份有限公司内部传阅，禁止外泄以及用于其他的商业目
 */  
package com.nbst.comnutil;

import java.util.ArrayList;
import java.util.List;

import org.springframework.util.StringUtils;

import com.nbst.model.base.Menu;

public class MenuTree {
	private StringBuffer html = new StringBuffer();
	private List<Menu> menus;

	public MenuTree(List<Menu> menus) {
		this.menus = menus;
	}

	public String buildTree() {
		html.append("<li class='active'><a th:href='/'>首页</a></li>");
		for (Menu menu : menus) {
			if(!menu.getpName().equals("报工台")) {
				if (StringUtils.isEmpty(menu.getpPid())) {
					html.append("<li onmouseover='MouseOver(this)' onmouseout='MouseOut(this)' class='dropdown'><a>"+menu.getpName()+"<b class='caret'></b></a><ul class='dropdown-menu'>");
					build(menu);
					html.append("</ul></li>");
				}
			}
			
		}
		return html.toString();
	}

	private void build(Menu menu) {
		List<Menu> children = getChildren(menu);
		if (!children.isEmpty()) {
//			html.append("<li class='dropdown'><a class='dropdown-toggle' data-toggle='dropdown'>"+menu.getpName()+"<b class='caret'></b></a><ul class='dropdown-menu'>");
			for (Menu child : children) {
				String id = child.getpId();
				List<Menu> childrens = getChildren(child);
				if(childrens.isEmpty()){
					html.append("<li><a href='javascript:;' addtabs='" + id + "' url='"+ child.getpUrl() + "' icon='" + child.getBtIcon() +"'>" + child.getpName() + "</a></li>");
					build(child);
				}else{
					html.append("<li class='dropdown-submenu'><a>"+ child.getpName() +"</a><ul class='dropdown-menu'>");
					build(child);
					html.append("</ul></li>");
				}
			}
		}
	}

	private List<Menu> getChildren(Menu menu) {
		List<Menu> children = new ArrayList<Menu>();
		String id = menu.getpId();
		for (Menu child : menus) {
			if (id.equals(child.getpPid())) {
				children.add(child);
			}
		}
		return children;
	}
}